package com.jiuzhi.app.common.wxutil;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiuzhi.app.common.util.*;
import com.jiuzhi.app.common.wxutil.model.HttpUtils;
import com.jiuzhi.app.common.wxutil.model.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class TokenUtil {
    public static String appId = "wx9e6031cb12e760e3";
    public static String secret = "b34e16f12fc259488243a4487d81c0a7";
    public static String wxurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    // 获取jsapi_ticket签名
    public static final String ticketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";
    public static String token = "abcabc";
    public static String mchId = "1511829211";
    //用户授权地址;
    public static final String sitePath = "http://www.9zhinet.com";
    //获取微信公众号支付支付信息
    public static final String PAY_INFO = "CHARGE:PAY:INFO:S:KEY[%s]";
    //微信支付秘钥
    public static String paysecret = "fdjnskfds2sd2f2sfsdf212sdf2dfsbb";
    //调用充电桩服务地址
   // public static String chargeurl = "http://172.16.10.75:8112/cardsystemapi";


    @Autowired
    RestTemplate restTemplate;
    public final Logger logger = LoggerFactory.getLogger(this.getClass());



    /**
     * access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。
     * access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时，需定时刷新，
     * 重复获取将导致上次获取的access_token失效。 获取微信访问令牌accessToken
     */
    public String getAccessToken() {
        String accessToken = null;
        try {
            String httpUrl = wxurl + "&appId=" + appId + "&secret=" + secret;

                HttpResult httpResult = HttpUtil.httpGet(httpUrl);
                String result = httpResult.getResult();
                Map<String, String> map = new ObjectMapper().readValue(result, Map.class);

                logger.info("设置token："+map.get("access_token"));
                accessToken = map.get("access_token").replaceAll("\\\"","");
                logger.info("获取token："+accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 获取jsapi_ticket
     *
     * @return
     */
    public String getJsapiTicket() {
        String jsapiTicket = null;
        try {
            String httpUrl = ticketURL + "access_token=" + getAccessToken() + "&type=jsapi";

            //判断是否过期 日过过期重新获取 不过期从redis获取


                HttpResult httpResult = HttpUtil.httpGet(httpUrl);
                String result = httpResult.getResult();
                Map<String, String> map = JsonTool.jsonStringToMapStr(result);
                jsapiTicket = map.get("ticket");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsapiTicket;
    }

    public String buildOauth2UrlByBase(String redirectUrl, String state) {
        StringBuilder url = new StringBuilder();
        url.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
        url.append(appId);
        url.append("&redirect_uri=").append(SignUtil.urlEncode(redirectUrl));
        url.append("&response_type=").append("code");
        url.append("&scope=").append("snsapi_base");
        if (StringUtils.isNotEmpty(state)) {
            url.append("&state=").append(state);
        }
        url.append("#wechat_redirect");
        return url.toString();
    }

    /**
     * 获取openId
     *
     * @param request
     * @param response
     * @return
     */
    public String getOpenIdFromRequest(HttpServletRequest request, HttpServletResponse response) {
        //先从cookie中查找，若找到，说明已经登录过
        boolean canShow = false;
        String openId = HttpUtils.getCookieByName(request, "wxs_open_id");
        if (StringUtils.isEmpty(openId)) {
            String code = request.getParameter("code");
            if (StringUtils.isEmpty(code)) {
                //还没有开始验证
                //cookie中没有记录openId，重定向到oauth2链接中验证身份
                try {
                    String redirectUrl = sitePath + request.getRequestURI();
                    if (StringUtils.isNotEmpty(request.getQueryString())) {
                        redirectUrl += "?" + request.getQueryString();
                    }
                    redirectUrl = buildOauth2UrlByBase(redirectUrl, null);
                    System.out.println("----redirectUrl----" + redirectUrl);
                    response.sendRedirect(redirectUrl);
                    System.out.println(("没有找到userid,重定向到： " + redirectUrl));
                    return null;
                } catch (IOException ignored) {
                }
            }
            Map<String, Object> data = null;
            try {
                data = getWxUserInfoByCode(request.getParameter("code"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (data == null || data.size() == 0) {
                R.error().put("msg", "微信服务器无响应，请返回消息列表重新打开！");
                return null;
            }
            openId = (String) data.get("openid");
            if (StringUtils.isNotEmpty(openId)) {
                //登录成功
                canShow = true;
                HttpUtils.addCookie(response, "wxs_open_id", openId, 3600);
            }
        } else {
            System.out.println(String.format("从cookie中获取到的userid：%s ", openId));
            canShow = true;
        }
        if (!canShow) {
            //没有权限查看此页面
            R.error().put("err", "对不起，数据已失效，请返回消息列表重新打开！");
            return null;
        }
        if (StringUtils.isEmpty(openId)) {
            R.error().put("err", "对不起，数据已失效，请返回消息列表重新打开！");
        }
        return openId;
    }

    /**
     * 获取用户的信息
     *
     * @param code
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public Map<String, Object> getWxUserInfoByCode(String code) throws ClientProtocolException, IOException {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code="
                + code + "&grant_type=authorization_code";
        HttpResult response = HttpUtil.httpGet(url);
        String result = response.getResult();
        System.out.println(result);
        Map<String, Object> map = new ObjectMapper().readValue(result, Map.class);
        return map;
    }

    //微信获取用户基本信息
    public JSONObject getWechatUserInfo(String openId) {
        String access_token = getAccessToken();
        JSONObject postData = new JSONObject();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openId;
        JSONObject result = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
        System.out.println(result);
        return result;
    }

}
